# -*- coding: UTF-8 -*-

import sys
import time
import json
import requests
import processbar 

def GenerateOneText(sApi, iRate, iStart, iNum, sType, iFlag):
    """生成一言文本"""
    
    """
    sApi: 调用接口
    iRate: 调用接口频率
    iStart: 生成的开始编号
    iNum: 生成一言总数
    sType: 一言语句类型
    iFlag: 是否重新生成
    ---------------------
    a：动画     b：漫画
    c：游戏     d：文学
    e：原创     f：来自网络
    g：其他     h：影视
    i：诗词     j：网易云
    k：哲学     l：抖机灵
    ---------------------
    """
    dtext = {}
    if iFlag:
        iStart = 0
    iTotal = iNum + iStart
    dtext['total'] = iTotal
    if sType:
        sApi = "".join([sApi, '/?c=', sType])
    process_bar = processbar.ShowProcess(iNum)
    for i in range(iNum):
        response = requests.get(sApi)
        sText = response.text
        dData = json.loads(sText)
        dNewData = {}
        hitokoto = dData.get("hitokoto", "")
        source = dData.get("from", "")
        creator = dData.get("creator", "")
        timenow = time.time()
        update = dData.get("created_at", timenow)
        if not update.isdigit():
            update = timenow
        else:
            update = abs(int(update))
        update = min(update, timenow)
        update = time.localtime(update)
        update = time.strftime("%Y-%m-%d %H:%M:%S", update)
        dNewData.update({"hitokoto":hitokoto, "from":source, "creator":creator, "update":update})
        dtext[str(i+iStart+1)] = dNewData
        process_bar.show_process()
        time.sleep(iRate)
    process_bar.close()
    return dtext

if __name__ == "__main__":
    sApi = "https://v1.hitokoto.cn"
    iRate = float(sys.argv[1])
    iNum = int(sys.argv[2])
    sType = sys.argv[3]
    sPath = sys.argv[4]
    iFlag = int(sys.argv[5])
    json_old = json.load(open(sPath, "r", encoding="utf-8"))
    iStart = int(json_old['total'])
    dtext = GenerateOneText(sApi, iRate, iStart, iNum, sType, iFlag)
    json_old.update(dtext)
    if iFlag:
        json_old = dtext
    json_new = json.dumps(json_old, ensure_ascii=False, indent=4)
    with open(sPath, "w", encoding="utf-8") as fw:
        fw.write(json_new)
